const axios = require('axios');
const io = require('socket.io-client');

const API_BASE = 'http://localhost:3000';

async function testVoiceCall() {
  console.log('🎤 开始测试语音通话功能...\n');
  
  try {
    // 1. 创建测试会话
    console.log('1. 创建测试会话...');
    const createChatRes = await axios.post(`${API_BASE}/chats/openOrCreate`, {
      fromUserId: 'test_user_001',
      targetType: 'doctor',
      targetId: 'doctor_001',
      targetName: '测试医生'
    });
    
    console.log('✅ 创建会话成功:', createChatRes.data);
    const chatId = createChatRes.data._id;
    const doctorVirtualId = `doctor_${createChatRes.data.targetInfo.id}`;
    console.log('医生虚拟ID:', doctorVirtualId);
    
    // 2. 模拟移动端Socket连接
    console.log('\n2. 模拟移动端Socket连接...');
    const mobileSocket = io(API_BASE, { 
      query: { userId: 'test_user_001' },
      transports: ['websocket']
    });
    
    await new Promise((resolve) => {
      mobileSocket.on('connect', () => {
        console.log('✅ 移动端Socket连接成功');
        resolve();
      });
    });
    
    // 3. 模拟PC端Socket连接
    console.log('\n3. 模拟PC端Socket连接...');
    const pcSocket = io(API_BASE, { 
      query: { userId: doctorVirtualId },
      transports: ['websocket']
    });
    
    await new Promise((resolve) => {
      pcSocket.on('connect', () => {
        console.log('✅ PC端Socket连接成功');
        resolve();
      });
    });
    
    // 4. 设置PC端事件监听
    console.log('\n4. 设置PC端事件监听...');
    let voiceCallReceived = false;
    
    pcSocket.on('voice:incoming', (payload) => {
      console.log('📞 PC端收到语音通话邀请:', payload);
      voiceCallReceived = true;
      
      // 模拟接听
      setTimeout(() => {
        console.log('📞 PC端接听语音通话...');
        pcSocket.emit('voice:answer', {
          callId: payload.callId,
          answer: { type: 'answer', sdp: 'mock-answer-sdp' },
          to: 'test_user_001'
        });
      }, 1000);
    });
    
    // 5. 移动端发起语音通话
    console.log('\n5. 移动端发起语音通话...');
    const callId = `voice_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    mobileSocket.emit('voice:forward', {
      to: doctorVirtualId,
      callId: callId,
      from: 'test_user_001',
      fromName: '测试用户'
    });
    
    console.log('📤 语音通话邀请已发送');
    
    // 6. 等待PC端接收
    console.log('\n6. 等待PC端接收...');
    await new Promise((resolve) => {
      const timer = setTimeout(() => {
        if (!voiceCallReceived) {
          console.log('❌ PC端未收到语音通话邀请');
        }
        resolve();
      }, 5000);
      
      if (voiceCallReceived) {
        clearTimeout(timer);
        resolve();
      }
    });
    
    // 7. 清理
    console.log('\n7. 清理连接...');
    mobileSocket.disconnect();
    pcSocket.disconnect();
    
    if (voiceCallReceived) {
      console.log('\n🎉 语音通话测试成功！');
    } else {
      console.log('\n❌ 语音通话测试失败！');
    }
    
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
  }
}

// 运行测试
testVoiceCall();
